package com.mac.userinfo.usermanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mac.common.util.BusinessException;
import com.mac.common.util.ExcelUtil;
import com.mac.common.util.Util;
import com.mac.core.page.PageBean;
import com.mac.userinfo.usermanage.mapper.UserManageMapper;
import com.mac.userinfo.usermanage.service.IUserManageService;
import com.mac.userinfo.usermanage.vo.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserManageServiceImpl implements IUserManageService {
	private final Logger log =  LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserManageMapper userManageMapper;

	@Override
	public PageInfo<UserInfoVO> queryAllInfo(UserInfoVO vo, int currentPage,int pageSize) {
		log.info("查询所有用户信息=====");
		//设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
		PageHelper.startPage(currentPage, pageSize);
		List<UserInfoVO> allInfo = userManageMapper.queryAllInfo(vo);
		PageInfo<UserInfoVO> pageData = new PageInfo<UserInfoVO>(allInfo);
		return pageData;
	}

	@Override
	public void insertInfo(UserInfoVO vo) {

	}

	@Override
	public int addBatch(InputStream in, String column, Map<String, Map<String, Object>> maPara) throws Exception, IOException {
		log.info("通过Excel导入 批量保存");
		List<Map<String, Object>> dataList = ExcelUtil.readExcel(in, false);
		/**
		 * 执行导入保存数据
		 */
		return this.executeInsertAddBatch(dataList, maPara);
	}

	/**
	 * 执行批量插入操作
	 *
	 * @param lists 要保存的数据
	 */
	private int executeInsertAddBatch (List<Map<String, Object>> lists, Map<String, Map<String, Object>> maPara) {
		UserInfoVO vo = null;
		int num = 0;
		/**
		 * 插入数据处理
		 */
		for (Map<String, Object> map : lists) {
			//vo = ExcelUtil.mapToBean(UserInfoVO.class, map, maPara);

			map.put("JLZT","1");
			map.put("CREATETIME", new Date());
			map.put("XH", Util.getXh());
			map.put("USERPWD", Util.BCrypt(String.valueOf(map.get("USERPWD"))));
		}
		return this.insertBatch(lists);
	}

	@Override
	public int insertBatch(List<Map<String, Object>> voList) {
		log.info("批量插入START...");
		try {
			int num = userManageMapper.insertBatch(voList);
			log.info("批量插入 " + num + " 条记录！");
			return num;
		} catch (Exception e) {
			log.error("插入失败，原因：" + e);
			throw new BusinessException("数据库保存异常！请联系管理员");
		}

	}
}